define(['jquery', 'text!../../Content/calendar/calendar.html', 'common', 'knockout', 'fullcalendar', 'vendor/jquery.simplemodal'], function($, html, common, ko, fullcalendar, simplemodal){

	var container,
		calendarData,
		$mycalendar,
		isCalendarCreated = false;

	function init(c){
		container = $(c);
		container.html(html);
		loadTeamNav();
		bindEvents();
	}

	function onclose(){
		$('#simplemodal-overlay, #simplemodal-container').hide();
	}

	function bindEvents(){
		var browserHeight = $(window).height() - 100;  
	    var browserWidth = $(window).width() - 50;	

		common.subscribe('calendar/open', function(){
			if(!isCalendarCreated){
				$mycalendar.modal({close: false, opacity: 70, overlayClose: true, minWidth: browserWidth, minHeight: browserHeight, onClose: onclose, handleWindowResize: true });
				$mycalendar.fullCalendar( 'render' );
				isCalendarCreated = true;
			}
			else
				$('#simplemodal-overlay, #simplemodal-container').show();
		});
	}

	function getCompactDate(date) {
		return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
	}

	function getDataByDate(date){
		var res = [];
		for(var i = 0; i < calendarData.length; i++){
			if(getCompactDate(calendarData[i].StartDate) == date){
				res.push(calendarData[i]);
			}
		}
		return res;
	}

	function getDataById(id){
		for(var i = 0; i < calendarData.length; i++){
			/*
			console.log("calendar ID: "+ calendarData[i].id);
			console.log("ID: "+ id);
			*/
			if(calendarData[i].id == id){
				return calendarData[i];
			}
		}
	}

	function openDetail(el, params, e){
		var data = getDataById(params.id);
		$mycalendar.find('.fc-event').css('z-index', 0);
		$mycalendar.find('.details').remove();

		var detailsDiv = $("<div class='details'>\
			<h3>"+data.Title+" <a href='#' class='closeDetails'></a></h3>\
			<div class='date'>\
				<ul>\
					<li class='dateLi'><span>" + data.FormattedStartDate + "</span></li>\
					<li class='hourLi'><span>"+ data.FormattedStartTime+"</span></li>\
				</ul>\
			</div>\
			<div class='agenda'><h2>Agenda</h2>" + data.AgendaNotes + "\
			<div class='meetingMinutes'><a href="+data.MeetingMinutesUrl + ">Meeting Minutes</a></div></div>\
			</div>");
		$(el).css('z-index', 10).append(detailsDiv);
		if(e.pageX > Math.floor(($(window).innerWidth()+100)/2)){
			$(".details").addClass('right');
		}else{
			$(".details").addClass('left');
		}

		if(e.pageY > Math.floor(($(window).innerHeight()+100)/2)){
			var bottom = e.pageY.toString();
			//console.log($("#calendar").height()));
			$(".details").css({"top":"auto","bottom": "-150%"});
		}

		detailsDiv.on('click', 'a.closeDetails', function(e){
			e.preventDefault();
			e.stopPropagation();
			$(this).closest('fc-event').css('z-index', 0);
			$(this).off('click').closest('.details').remove();
		});
	}

	var viewModel = {
		Calendar : ko.observable()
	};

	function formateTime(strTime){
		var tmpTime = strTime.split(':'),
			suffix = parseInt(tmpTime[0]) > 12 ? 'PM' : 'AM';

		return tmpTime[0] + '.' + tmpTime[1] + ' ' + suffix;
	}

	function createCalendar(data){
		container.find('.calendar-widget').fullCalendar({
			header: {
				left: 'icon,prev,today',
				center: 'agendaDay agendaWeek month title',
				right: 'next,closeBtn, plus'
			},
			events: data,
			eventDrop: function(event, delta) {
				alert(event.title + ' was moved ' + delta + ' days\n' +
					'(should probably update your database)');
			},
			loading: function(bool) {
				if (bool) $('#loading').show();
				else $('#loading').hide();
			},
			eventClick: function(data, e) {
				if($(e.target).parents('.fc-event-inner').length > 0)
					openDetail(this, data, e);
			},
			eventRender: $.proxy(function(event, element) {

				var data = getDataById(event.id);
				element.find('.fc-event-inner').find('.fc-event-time').html(data.FormattedStartTime);

			}, this),
			dayRender: function(date, cell){
			var data = getDataByDate(getCompactDate(date));				
				if(data && data.length){
					cell.addClass('active-week');					
				}
			}
		});
		$mycalendar = $('#calendar');

		$('.fc-button-closeBtn').click($.proxy(function(e) {
			onclose();
		}, this));

	}

	function processData(rawData){
		var info = [],
			tempDate,
			tempTime;
		for(var i = 0; i < rawData.length; i++){
			var node = {
				"id" : rawData[i].id,
				"title" : rawData[i].Title
			};
			if(rawData[i].StartDate){
				node.start = eval(" new " + rawData[i].StartDate.replace(/(\\|\/)/g, ''));
				rawData[i].StartDate = node.start;
			}
			if(rawData[i].EndDate){
				node.end = eval(" new " + rawData[i].EndDate.replace(/(\\|\/)/g, ''));
				rawData[i].EndDate = node.end;
			}
			if(rawData[i].allDay){
				node.allDay = rawData[i].allDay;
			} else {
				node.allDay = false;
			}

			info.push(node);
		}
		return info;
	}

	function loadTeamNav(){
		common.service('calendar.json').success(function(data){
			calendarData = data;
			var process = processData(data);
			console.log(process);
			createCalendar(process);
			/* ko.applyBindings(viewModel, container[0]); */
		});
	}


	return {
		"init" : init
	};


});